package com.iw.adoms.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import com.iw.adoms.entity.Brand;
import com.iw.adoms.entity.Department;
import com.iw.adoms.entity.Marchandise;
import com.iw.adoms.entity.MarchandiseType;
import com.iw.adoms.service.BrandService;
import com.iw.adoms.service.MarchandiseService;
import com.iw.adoms.service.MarchandiseTypeService;
import com.iw.core.orm.PageData;
import com.iw.core.security.entity.Users;
import com.iw.core.utils.WebUtils;

@Controller
@RequestMapping("/adoms/marchandise")
public class MarchandiseAction {
	@Resource
	private MarchandiseService marchandiseService;
	@Resource
	private MarchandiseTypeService marchandiseTypeService;
	@Resource
	private BrandService brandService;

	@RequestMapping("/list")
	public ModelMap list(HttpServletRequest request) {
		PageData<Marchandise> pageData = new PageData<Marchandise>();
		// 给pageData设置参数
		WebUtils.setPageDataParameter(request, pageData);
		pageData = marchandiseService.find(pageData);

		return new ModelMap(pageData);
	}

	@RequestMapping("/myList")
	public ModelMap myList(HttpServletRequest request) {
		PageData<Marchandise> pageData = new PageData<Marchandise>();
		// 给pageData设置参数
		WebUtils.setPageDataParameter(request, pageData);
		pageData.getPagination().setPageSize(1000);
		pageData = marchandiseService.find(pageData);

		List<Marchandise> mList = new ArrayList<Marchandise>();
		List<Marchandise> mAll = pageData.getResult();
		Integer did = getCurrentUser(request).getDepartment().getId();
		List<Brand> allBrand = brandService.findAll();
		Set<Brand> myBrands = new HashSet<Brand>();
		for (Brand b : allBrand) {
			Set<Department> departs = b.getDepartment();
			for (Department d : departs) {
				if (d.getId().equals(did)) {
					myBrands.add(b);
				}
			}
		}
		// 只取代理的品牌下面的代理商品
		for (Marchandise m : mAll) {
			for (Brand b : myBrands) {
				if (b.getId().equals(m.getBrand().getId())) {
					if (!mList.contains(m)) {
						mList.add(m);
					}
				}
			}
		}

		pageData.setResult(mList);

		return new ModelMap(pageData);
	}

	@RequestMapping(value = "/new")
	public String addForm(Model model) {
		commonModel(model);
		return "/adoms/marchandise/input";
	}

	@RequestMapping(value = "/edit/{id}")
	public String editForm(@PathVariable("id") Integer id, Model model) {
		Marchandise marchandise = marchandiseService.find(id);
		model.addAttribute(marchandise);
		commonModel(model);
		return "/adoms/marchandise/input";
	}

	private void commonModel(Model model) {
		List<MarchandiseType> typeList = marchandiseTypeService.findAll();
		model.addAttribute("typeList", typeList);
		List<Brand> brandList = brandService.findAll();
		model.addAttribute("brandList", brandList);
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(Marchandise marchandise) {
		if (marchandise.isNew()) {
			marchandiseService.save(marchandise);
		} else {
			marchandiseService.update(marchandise);
		}

		return "redirect:/adoms/marchandise/list";// 重定向
	}

    @RequestMapping(value = "/repeat")
    @ResponseBody
    public boolean repeat(String value, Integer id, String property) {
        try {
            List<Marchandise> marchandises = marchandiseService.findList(property, value);
            if (marchandises != null && marchandises.size() > 0) {
                if (id != 0) {
                    Marchandise m = marchandiseService.find(id);
                    if (property.equals("name") && !m.getName().equals(value)) {
                        return false;
                    } else if (property.equals("code") && !m.getCode().equals(value)) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

	@RequestMapping(value = "/delete/{id}")
	public String delete(@PathVariable("id") Integer id) {
		marchandiseService.delete(id);
		return "redirect:/adoms/marchandise/list";// 重定向
	}

	@RequestMapping(value = "/visible/{id}")
	public String visible(@PathVariable("id") Integer id) {
		marchandiseService.visible(id);
		return "redirect:/adoms/marchandise/list";// 重定向
	}

	@RequestMapping(value = "/unVisible/{id}")
	public String unVisible(@PathVariable("id") Integer id) {
		marchandiseService.unVisible(id);
		return "redirect:/adoms/marchandise/list";// 重定向
	}

	@RequestMapping(value = "/detail/{id}")
	public String detail(@PathVariable("id") Integer id, Model model) {
		Marchandise m = marchandiseService.find(id);
		model.addAttribute("m", m);
		return "/adoms/marchandise/detail";// 重定向
	}

	@InitBinder
	public void InitBinder(WebDataBinder dataBinder) {
		dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
	}

	private Users getCurrentUser(HttpServletRequest request) {
		Users user = (Users) request.getSession().getAttribute("USER");
		return user;
	}

}
